
 if (typeof SonicPortal != "object") SonicPortal = new Object();

Object.extend(SonicPortal, 
{
    loader: new Image(),
    loader_src: '/img/ajax-loader.gif',
     
    //Shows a lightbox with a given string
    showLightboxText: function(textContent, close_button, loading_indicator, callback, width)
    {
        this.config = {};
        	
		var style;
        if (width) style = "width: " + width + "px";
        else style = ""
        this._lightBox('<div id="lightbox_default" style="' + style + '">' + textContent + '</div><br/>', close_button, loading_indicator, callback);
    },
    
    //Shows a lightbox with from a given existing div.  Bad idea for forms.
    showLightboxFromDiv: function(source_div, close_button, loading_indicator, callback)
    {
        this.config = {};
        
        if (typeof source_div == "string") source_div = $(source_div);
        source_div.setStyle({position: 'absolute', display: "block", top :  (Position.page(document.body)[1]*-1 + 100)  + 'px'});
        this.centerElement(source_div, document.body);
		this._box = source_div;
		if ($("lb_close")) $("lb_close").remove();
        if (close_button) this._box.innerHTML += '<div id="lb_close"><a class="small_button small_stroke_button small_brown_stroke" style="float:right; margin-bottom: 6px" onclick="SonicPortal.closeLightbox()" ><span>Close</span></a><br/></div>';
        
        document.body.appendChild(this._box);
        this.addOpaque();
        this._box.show();
		
		if (typeof callback == "function") callback();
    },
    
    //Shows a lightbox from a given URL.  The parent div of this content needs a background color and definted width
    showLightboxAjax: function(url, close_button, loading_indicator, callback, _params, config)
    {
        this.showLightboxText('Loading...<br/>', false, true);
        
        if (!config) config = {};
        this.config = config;

        new Ajax.Request(url, {
            parameters: _params,
            onSuccess: 
            function(data) {
                SonicPortal._lightBox(data.responseText, close_button, loading_indicator, callback)
            }
        });
               
    },
    
    //Removes a lightbox.  There can only be one
    closeLightbox: function()
    {
        if (typeof SonicPortal.config.onClose == "function") SonicPortal.config.onClose(); 
      	SonicPortal._box.hide();
        Element.hide($('loading_opaque'));

    },
    
    addOpaque: function()
    {
    	if (!$('loading_opaque'))
    	{
        	var opaque = document.createElement('div');
            Element.extend(opaque);
            
        	opaque.id = 'loading_opaque';
            opaque.observe('click', SonicPortal.closeLightbox);
            
    	    var styles = { 
                background: '#333333',
                width: '100%',
                position: 'fixed',
                display: 'block',
                height: '100%'
            };
            
            document.body.appendChild(opaque);
    	    $('loading_opaque').setStyle(styles);
    	}
    	else $('loading_opaque').setStyle({display: 'block'});
    	
    },
    
    _lightBox: function(textContent, close_button, loading_indicator, callback)
    {
        if ($('lightbox_container')) Element.remove($('lightbox_container')); 
                
        //Our tooltips would be on top of the opaque bg.
    	if (typeof hideTooltips == "function") hideTooltips();
    	
    	var styles = { 
                background: '#333333',
                display: 'block',
                width: '100%',
                height: document.documentElement.scrollHeight + "px"
            };
    	    	
        
    	//Using spans to prevent the 'div is as big as body' issue in IEs
    	var box = document.createElement('span');
    	box.id = 'lightbox_container'; 
    	box.innerHTML = textContent;
    	document.body.appendChild(box);
    	//document.body.insertBefore(box, document.body.childNodes[0]);
    	        
        var control_wrap = document.createElement('span');
        control_wrap.id = 'lightbox_control_wrap';
        
    	if (loading_indicator) {
            SonicPortal.loader.src = SonicPortal.loader_src;
            SonicPortal.loader.className = "ajax_loader";
            control_wrap.appendChild(SonicPortal.loader);
        }
        
        if (close_button) {
            control_wrap.innerHTML += '<a class="small_button small_stroke_button small_brown_stroke" style="float:right; margin-bottom: 6px" onclick="SonicPortal.closeLightbox()" ><span>Close</span></a><br/>';
        }
        
        this.addOpaque();
        $('lightbox_container').descendants()[0].appendChild(control_wrap);
        
    	// set the style of the element so it is centered
    	styles = { 
    		top :  (Position.page(document.body)[1]*-1 + 100)  + 'px',
    		display: 'block'
    		
    	};
    
    	$('lightbox_container').setStyle(styles);			
    	this.centerElement($('lightbox_container'), document.body);
         
        this._box = $('lightbox_container');
        if (typeof callback == "function") callback();      
    },
    
    //Simple lightbox updator w built in form post
    lightboxSubmit: function(form, url, update_el, callback)
    {
		if (!update_el) update_el = $('lightbox_container');
        new Ajax.Request(url, {
            parameters: form.serialize(true),
            method: 'POST',
            onSuccess: function(response){
                if (update_el) update_el.update(response.responseText);
                if (typeof callback == "function") callback();
            }});        
    },
    
    /*Creates the green/red message for success or failure, wants JSON like
    {status: 'saved|error|this will become the class of the div', text: [Goes in the div]}
    */
    lightboxMessage: function(message_div, response)
    {
        message_div.innerHTML = response.text;
        message_div.className = response.status;
        message_div.show();
        Effect.Fade(message_div, {delay: 2, duration: 2});
       
    },
    
    //Prototype 1.5 is missing this.  Must add element to DOM before this works.
    centerElement: function(element, parent)
    {

        var w, h, pw, ph;
        var d = Element.getDimensions(element);
        w = d.width;
        h = d.height;
        Position.prepare();
        if (!parent) {
                var ws = Position.GetWindowSize();
                pw = ws[0];
                ph = ws[1];
        } else {
                pw = parent.offsetWidth;
                ph = parent.offsetHeight;
        }
        //Vertical centering still having issues.  Lightboxes are 100px from the top of the screen for now.
        //element.style.top = (ph/2) - (h/2) -  Position.deltaY + "px";
        element.style.left = (pw/2) - (w/2) -  Position.deltaX + "px";

    }
});

SonicPortal.Tabs = {};
SonicPortal.Tabs.loader = document.createElement('div');
SonicPortal.Tabs.loader.id = "tab_loader";

SonicPortal.tables = [];

//SonicPortal.Tabs namespace methods
Object.extend(SonicPortal.Tabs, 
{
    //Changes to the tab of the given id.  If redirect is given, we send them to that id as anchor text.
    changeTab: function(tab_id, redirect, callback)
    {
        if (tab_id.length == 0) return false;
        
        var active_tab = $(tab_id);
        SonicPortal.ACTIVE_TAB = $(tab_id);
        
        if (active_tab.className == "tab") 
        {
            SonicPortal.TABS.each(function(tab) {tab.className = "tab"});
            active_tab.className = "tab active";
            if (redirect) document.location = document.location.protocol + '//' + document.location.hostname + document.location.pathname + '#/' + SonicPortal.ACTIVE_TAB.id;
            
            var ajax;
            if (ajax = Element.readAttribute(SonicPortal.ACTIVE_TAB, "ajax")) 
            {
                $('tab_content').appendChild(SonicPortal.Tabs.loader);
                
                var html_callback = eval(Element.readAttribute(SonicPortal.ACTIVE_TAB, "callback"));

                if (html_callback)
                {
                    if (typeof html_callback == "function") callback = html_callback;
                }
                
                new Ajax.Updater('tab_content', ajax, {onSuccess: callback});
            }
            
            var table;
            if (table = Element.readAttribute(SonicPortal.ACTIVE_TAB, "datatable")) 
            {
                $('tab_content').appendChild(SonicPortal.Tabs.loader);
                SonicPortal.tables[SonicPortal.ACTIVE_TAB.id] = new DataTable({
                    baseURL: table,
                    element_id: "tab_content",
                    limit: 10,
                    dir: "ASC",
                    page: 1,
                    order_by: "properties.name"
                });
            }
        }        
    },
    
    //Refreshes tab user is on
    reloadTab : function()
    {
        var ajax;
        if (ajax = Element.readAttribute(SonicPortal.ACTIVE_TAB, "ajax")) 
        {
            $('tab_content').appendChild(SonicPortal.Tabs.loader);
            
            var html_callback = eval(Element.readAttribute(SonicPortal.ACTIVE_TAB, "callback"));

            if (html_callback)
            {
                if (typeof html_callback == "function") callback = html_callback;
            }
            
            new Ajax.Updater('tab_content', ajax, {onSuccess: callback});
        }
        
        var table;
        if (table = Element.readAttribute(SonicPortal.ACTIVE_TAB, "datatable")) 
        {
            $('tab_content').appendChild(SonicPortal.Tabs.loader);
            SonicPortal.tables[SonicPortal.ACTIVE_TAB.id] = new DataTable({
                baseURL: table,
                element_id: "tab_content",
                limit: 10,
                dir: "ASC",
                page: 1,
                order_by: "properties.name"
            });
        }     
    },
    
    listen: function()
    {
        window.setTimeout(SonicPortal.Tabs.listen, 500);
        if (typeof SonicPortal.ACTIVE_TAB == "undefined") return false;
         
        if (document.location.hash.length <= 0) SonicPortal.Tabs.changeTab(SonicPortal.TABS[0], false); 
        else if (document.location.hash != '#/' + SonicPortal.ACTIVE_TAB.id) SonicPortal.Tabs.changeTab(document.location.hash.replace('#/', ''), true); 
     
    }
}); 


SonicPortal.loader.src = SonicPortal.loader_src;

function multipleArtists(track_id, save)
{
	if (save) save = "/save";
	else save = "";
	
	new Ajax.Request("/job/multiple_track_artists/" + track_id + save, {onSuccess: function(response)
	{
		var artists = eval(response.responseText);
		var html = "";
		
		for (i=0; i<artists.length; i++)
		{
			html += artists[i].name + "<br/>";
		}
		
		html += '<a href="javascript: multipleArtists(' + track_id +', true)">Okay</a>';
		
		SonicPortal.showLightboxText(html, true);
	}
	});
}

function viewArtists(track_id, save)
{	
	SonicPortal.showLightboxAjax("/job/view_track_artists/" + track_id, true);
}

function setPrimaryArtist(track_id)
{
	new Ajax.Request("/job/set_primary_artist/" + track_id, 
	{
		parameters: $('set_primary_artist').serialize(true),
		onSuccess: function(response) {
			SonicPortal.showLightboxText(response.responseText);
		}
	});
}

function addTrackArtist(track_id)
{
	new Ajax.Request("/job/add_track_artist/" + track_id, 
	{
		parameters: $('add_track_artist').serialize(true),
		onSuccess: function(response) {
			SonicPortal.showLightboxText(response.responseText);
		}
	});
}

function deleteTrackArtist(track_id, artist_id)
{
	new Ajax.Request("/job/delete_track_artist/" + track_id + "/" + artist_id, 
	{
		onSuccess: function(response) {
			SonicPortal.showLightboxText(response.responseText);
		}
	});
}


Event.observe(window, 'load', function()
{
	$$(".dropdown").each(
		function(el)
		{
			console.log(el);
			var track_id = el.readAttribute("track_id");
			var menu_options = [];
			
			try
			{
				var menu = new CustomComponents.DropDownMenu(el.id);
			    menu_options.push({label: "Multiple Artists", link: "javascript: multipleArtists(" + track_id + ")"});
				menu_options.push({label: "View Track Artists", link: "javascript: viewArtists(" + track_id + ")"});
				
				if (menu_options.length)
				{
					//menu_options.sort(function(a, b) { if (a.label > b.label) return 1; else if (b.label > a.label) return -1; else return 0; });
					menu.create(menu_options, function(el) {}, "link", {iconFile: false});
					menu.setLabel("A");
				}
				else el.hide();
			}
			catch (e) {}
		});
});